package com.spring.security;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.spring.authManage.dao.UserInfoDao;
import com.spring.authManage.pojo.UserInfo;
import com.spring.common.constant.StatusConstant;
import com.spring.common.util.MD5;



public class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
	public static final String USERNAME = "j_username";
	public static final String PASSWORD = "j_password";
	private Logger logger=Logger.getLogger(CustomUsernamePasswordAuthenticationFilter.class);
	private UserInfoDao userInfoDao;


	public void setUserInfoDao(UserInfoDao userInfoDao) {
		this.userInfoDao = userInfoDao;
	}

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
		if (!request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
		}
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			logger.error("不支持编码:"+e1.getMessage());
		}
		String username = obtainUsername(request);
		String password = obtainPassword(request);
		if ("".equals(username)){
			throw new AuthenticationServiceException("用户名不能为空！"); 
		}
		if ("".equals(password)){
			throw new AuthenticationServiceException("密码不能为空！"); 
		}
		//验证用户账号与密码是否对应
		username = username.trim();
		UserInfo userInfo = null;
		try {
			userInfo = userInfoDao.queryUserInfoByUserName(username);
		} catch (Exception e) {
			logger.error("获取用户信息异常！");
		}
		if(userInfo == null || !password.equals(userInfo.getPassword())) {
			throw new AuthenticationServiceException("用户名或密码错误!"); 
		}
		if(userInfo ==null || StatusConstant.N.equals(userInfo.getStatus())) {
			throw new AuthenticationServiceException("无效的用户!"); 
		}
		
		//UsernamePasswordAuthenticationToken实现 Authentication
		UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
		// Place the last username attempted into HttpSession for views
		
		// 允许子类设置详细属性
        setDetails(request, authRequest);
		
        // 运行UserDetailsService的loadUserByUsername 再次封装Authentication
		return this.getAuthenticationManager().authenticate(authRequest);
	}
	
	@Override
	protected String obtainUsername(HttpServletRequest request) {
		Object obj = request.getParameter(USERNAME);
		return null == obj ? "" : obj.toString();
	}

	@Override
	protected String obtainPassword(HttpServletRequest request) {
		Object obj = request.getParameter(PASSWORD);
		return null == obj ? "" : MD5.getMD5Encode(obj.toString());
	}
	
	
}
